package gen.tools;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetTableColumnValue extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public GetTableColumnValue() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		final Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/text");
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		final String tableName = request.getParameter("tableName");
		final String columnName = request.getParameter("columnName");
		
		
		//限制條件
		String constraint = wid.stringFilter( request.getParameter("constraint") );
		
		if ( !"".equalsIgnoreCase(constraint) ) {
			constraint = " WHERE " + constraint.replaceAll(wid.splitTokenONE, "='");
			constraint = constraint.replaceAll(wid.splitTokenFOUR, "' AND ");
			constraint+="'";	
		}
		
		
		final String sql ="SELECT "+ columnName + " FROM " + tableName + constraint;
		System.out.println(sql);
		String columnValue ="";
		try {
			conn = wid.getConn();
			ps = conn.prepareStatement(sql);
			rs = ps.executeQuery();
			rs.next();
			columnValue = rs.getString( columnName );
			
		} catch( Exception e) {
			wid.errLog(e);
		} finally {
			try {
				if ( rs !=null ) { rs.close(); }
				if ( ps !=null ) { ps.close(); }
				if ( conn !=null ) { conn.close(); }
			} catch (Exception e) { e.printStackTrace(); }
		}
		
		response.getWriter().write( columnValue );
	}
}
